package com.youlu.campus.service.platform;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.common.utils.HttpClientUtil;
import com.youlu.campus.entity.AppUrlScheme;
import com.youlu.campus.entity.VO.res.WechatUrlSchemeResult;
import com.youlu.campus.service.wechat.WXacodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class AppUrlSchemeService {


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private WXacodeService wXacodeService;

    private final static String URL_SCHEME = "https://api.weixin.qq.com/wxa/generatescheme?access_token=%s";



    public String getAppToken(){
        return wXacodeService.getAccessToken();
    }



    /**
     * 目前只有微信小程序梦想 跳动一个APPID需要，则写死无需传参数
     *
     * @return
     */
    public String getUrlScheme(String appId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("appId").is(appId));
        AppUrlScheme appUrlScheme = this.mongoTemplate.findOne(query, AppUrlScheme.class);
        if (Objects.nonNull(appUrlScheme)) {
            return appUrlScheme.getUrl();
        }
        return remoteUrlScheme(appId);
    }

    private String remoteUrlScheme(String appId) {
        log.info("【获取微信链接】url scheme appId ->{} start ");
        try {
            String accessToken = wXacodeService.getAccessToken();
            String urlLink = String.format(URL_SCHEME, accessToken);
            Map<String, Object> paramMap = new HashMap(1);
            String result = HttpClientUtil.postJson(urlLink, paramMap, null, 3000, "utf8", 3, true);
            log.info(" 小程序的 URL Scheme appId ->{}| result ->{}", appId, result);
            if (StringUtils.isBlank(result)) {
                return "";
            }
            WechatUrlSchemeResult wechatUrlSchemeResult = JSON.parseObject(result, WechatUrlSchemeResult.class);
            if (Objects.isNull(wechatUrlSchemeResult)) {
                return "";
            }
            if (0 != wechatUrlSchemeResult.getErrcode()) {
                log.error("【小程序的 URL Scheme】错误 code -> {} | errormsg ->{}", wechatUrlSchemeResult.getErrcode(),
                        wechatUrlSchemeResult.getErrmsg());
                return "";
            }
            Query query = new Query();
            query.addCriteria(Criteria.where("appId").is(appId));
            AppUrlScheme appUrlScheme = this.mongoTemplate.findOne(query, AppUrlScheme.class);
            if (Objects.nonNull(appUrlScheme)) {
                return appUrlScheme.getUrl();
            }
            Date now = new Date();
            appUrlScheme = new AppUrlScheme();
            appUrlScheme.setAppId(appId);
            appUrlScheme.setUrl(wechatUrlSchemeResult.getOpenlink());
            appUrlScheme.setCreatedTime(now);
            appUrlScheme.setUpdatedTime(now);
            this.mongoTemplate.save(appUrlScheme);
            log.info("【获取微信链接】url scheme appId ->{} end ");
            return wechatUrlSchemeResult.getOpenlink();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("【小程序的 URL Scheme】错误 ", e);
            log.info("【获取微信链接】 URL Scheme appId ->{} end ");
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("【小程序的 URL Scheme 】错误 ", e);
            log.info("【获取微信链接】URL Scheme appId ->{} end ");
            return "";
        }
    }
}
